import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { ProductProps } from '@/types/storeType'

export const useProductStore = defineStore('product', () => {
  const products = ref<ProductProps[]>([])
  const loading = ref(false)
  const errorMsg = ref('')
  async function fetchProducts() {
    try {
      // 模拟 API 调用
      await new Promise((resolve) => setTimeout(resolve, 1000))

      products.value = [
        {
          id: 1,
          name: 'Vue.js 实战指南',
          description: '深入学习 Vue.js 的实用指南，包含最佳实践和实际项目案例。',
          price: 99.99,
          image: '/images/vue-book.jpg',
          category: 'books',
          featured: true,
          stock: 50,
        },
        {
          id: 2,
          name: 'React 开发手册',
          description: 'React 应用开发完整指南，从基础到高级特性。',
          price: 89.99,
          image: '/images/react-book.jpg',
          category: 'books',
          featured: true,
          stock: 30,
        },
        {
          id: 3,
          name: 'JavaScript 高级编程',
          description: 'JavaScript 高级特性和最佳实践详解。',
          price: 129.99,
          image: '/images/js-book.jpg',
          category: 'books',
          featured: false,
          stock: 25,
        },
        {
          id: 4,
          name: 'TypeScript 入门到精通',
          description: 'TypeScript 完整学习指南，包含实际项目应用。',
          price: 79.99,
          image: '/images/ts-book.jpg',
          category: 'books',
          featured: true,
          stock: 40,
        },
      ]
    } catch (err) {
      console.error(err)
      errorMsg.value = '获取产品列表失败'
    } finally {
      loading.value = false
    }
  }

  return {
    products,
    loading,
    errorMsg,
    fetchProducts,
  }
})
